package org.matsadaml.tool;

//Java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;

//FOP
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

/**
 * @author Björn 
 * 
 */
public class FopShop {

	private FopFactory Factory;
	private Templates CachedXslt;
	private String BaseDir;

	public FopShop(File xsltFile) throws IOException {
		super();
		//BaseDir = (new File(xsltFile.getParent())).getCanonicalPath();
		BaseDir = xsltFile.getParentFile().toURI().toString(); 
		// For this to work the Saxon jar must have been added in the Classpath
		System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
		// configure fopFactory as desired
		Factory = FopFactory.newInstance();
		Source xsltSource = new StreamSource(xsltFile);
		TransformerFactory transFact = TransformerFactory.newInstance();
		try {
			CachedXslt = transFact.newTemplates(xsltSource);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param xmlFile
	 * @param saveFile
	 * @throws Exception
	 */
	public void TransformAndSave(File xmlFile, File saveFile) throws Exception {
		try {

			// Setup output
			//saveFile.createNewFile();
			OutputStream out = new java.io.FileOutputStream(saveFile);
			out = new java.io.BufferedOutputStream(out);

			FOUserAgent foUserAgent = Factory.newFOUserAgent();
			// configure foUserAgent as desired
			foUserAgent.setBaseURL(BaseDir);

			try {
				// Construct fop with desired output format
				Fop fop = Factory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

				// Setup XSLT
				Transformer transformer = CachedXslt.newTransformer();

				// Setup input for XSLT transformation
				Source src = new StreamSource(xmlFile);

				// Resulting SAX events (the generated FO) must be piped through
				// to FOP
				Result res = new SAXResult(fop.getDefaultHandler());

				// Start XSLT transformation and FOP processing
				transformer.transform(src, res);
			} finally {
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		}

	};
}
